<!--
  属性面板组件
  显示和编辑选中图层的属性
-->
<template>
  <div class="properties-panel">
    <!-- 图层面板 -->
    <div class="panel-section">
      <div class="section-header">
        <n-text strong>图层</n-text>
        <n-button-group size="tiny">
          <n-button quaternary @click="addLayer">
            <template #icon>
              <n-icon><AddOutline /></n-icon>
            </template>
          </n-button>
          <n-button quaternary @click="deleteSelectedLayers" :disabled="!hasSelection">
            <template #icon>
              <n-icon><TrashOutline /></n-icon>
            </template>
          </n-button>
        </n-button-group>
      </div>
      
      <div class="layers-list">
        <n-scrollbar style="max-height: 200px;" :x-scrollable="false">
          <div
            v-for="layer in layersInOrder"
            :key="layer.id"
            class="layer-item"
            :class="{ selected: isLayerSelected(layer.id) }"
            @click="selectLayer(layer.id, $event)"
          >
            <div class="layer-controls">
              <n-button 
                quaternary 
                size="tiny"
                @click.stop="toggleLayerVisibility(layer.id)"
              >
                <template #icon>
                  <n-icon>
                    <component :is="layer.visible ? EyeOutline : EyeOffOutline" />
                  </n-icon>
                </template>
              </n-button>
              
              <n-button 
                quaternary 
                size="tiny"
                @click.stop="toggleLayerLock(layer.id)"
              >
                <template #icon>
                  <n-icon>
                    <component :is="layer.locked ? LockClosedOutline : LockOpenOutline" />
                  </n-icon>
                </template>
              </n-button>
            </div>
            
            <div class="layer-info">
              <n-icon size="16" :color="getLayerTypeColor(layer.type)">
                <component :is="getLayerTypeIcon(layer.type)" />
              </n-icon>
              <span class="layer-name">{{ layer.name }}</span>
            </div>
          </div>
        </n-scrollbar>
      </div>
    </div>
    
    <!-- 属性编辑面板 -->
    <div v-if="selectedLayer" class="panel-section">
      <div class="section-header">
        <n-text strong>属性</n-text>
      </div>
      
      <div class="properties-content">
        <n-scrollbar style="max-height: 400px;">
          <n-form :model="layerProperties" size="small" label-placement="left" label-width="60">
            <!-- 基本属性 -->
            <n-form-item label="名称">
              <n-input 
                v-model:value="layerProperties.name"
                @blur="updateLayerProperty('name', layerProperties.name)"
              />
            </n-form-item>
            
            <!-- 位置 -->
            <n-form-item label="位置">
              <n-input-group>
                <n-input-number
                  v-model:value="layerProperties.position.x"
                  :precision="1"
                  :step="1"
                  placeholder="X"
                  @blur="updateLayerProperty('position', layerProperties.position)"
                  style="width: 50%"
                />
                <n-input-number
                  v-model:value="layerProperties.position.y"
                  :precision="1"
                  :step="1"
                  placeholder="Y"
                  @blur="updateLayerProperty('position', layerProperties.position)"
                  style="width: 50%"
                />
              </n-input-group>
            </n-form-item>
            
            <!-- 缩放 -->
            <n-form-item label="缩放">
              <n-input-group>
                <n-input-number
                  v-model:value="layerProperties.scale.x"
                  :precision="2"
                  :step="0.1"
                  :min="0.01"
                  placeholder="X"
                  @blur="updateLayerProperty('scale', layerProperties.scale)"
                  style="width: 50%"
                />
                <n-input-number
                  v-model:value="layerProperties.scale.y"
                  :precision="2"
                  :step="0.1"
                  :min="0.01"
                  placeholder="Y"
                  @blur="updateLayerProperty('scale', layerProperties.scale)"
                  style="width: 50%"
                />
              </n-input-group>
            </n-form-item>
            
            <!-- 旋转 -->
            <n-form-item label="旋转">
              <n-input-number
                v-model:value="layerProperties.rotation"
                :precision="1"
                :step="1"
                suffix="°"
                @blur="updateLayerProperty('rotation', layerProperties.rotation)"
                style="width: 100%"
              />
            </n-form-item>
            
            <!-- 透明度 -->
            <n-form-item label="透明度">
              <n-slider
                v-model:value="layerProperties.opacity"
                :min="0"
                :max="100"
                :step="1"
                @update:value="updateLayerProperty('opacity', layerProperties.opacity)"
              />
              <n-input-number
                v-model:value="layerProperties.opacity"
                :min="0"
                :max="100"
                :step="1"
                suffix="%"
                @blur="updateLayerProperty('opacity', layerProperties.opacity)"
                style="width: 80px; margin-left: 8px"
              />
            </n-form-item>
            
            <!-- Z轴顺序 -->
            <n-form-item label="层级">
              <n-input-number
                v-model:value="layerProperties.zIndex"
                :min="0"
                :step="1"
                @blur="updateLayerProperty('zIndex', layerProperties.zIndex)"
                style="width: 100%"
              />
            </n-form-item>
          </n-form>
        </n-scrollbar>
      </div>
    </div>
    
    <!-- 关键帧面板 -->
    <div v-if="selectedLayer" class="panel-section">
      <div class="section-header">
        <n-text strong>关键帧</n-text>
        <n-button size="tiny" @click="addKeyframe">
          <template #icon>
            <n-icon><AddOutline /></n-icon>
          </template>
          添加
        </n-button>
      </div>
      
      <div class="keyframes-content">
        <n-scrollbar style="max-height: 150px;">
          <div v-if="layerKeyframes.length === 0" class="empty-keyframes">
            <n-text depth="3">暂无关键帧</n-text>
          </div>
          
          <div
            v-for="keyframe in layerKeyframes"
            :key="keyframe.id"
            class="keyframe-item"
            @click="selectKeyframe(keyframe.id)"
          >
            <div class="keyframe-time">
              {{ formatTime(keyframe.time) }}s
            </div>
            <div class="keyframe-properties">
              <n-tag size="tiny" v-for="prop in Object.keys(keyframe.value)" :key="prop">
                {{ prop }}
              </n-tag>
            </div>
            <n-button 
              quaternary 
              size="tiny"
              @click.stop="deleteKeyframe(keyframe.id)"
            >
              <template #icon>
                <n-icon><CloseOutline /></n-icon>
              </template>
            </n-button>
          </div>
        </n-scrollbar>
      </div>
    </div>
    
    <!-- 空状态 -->
    <div v-if="!selectedLayer" class="empty-state">
      <n-icon size="48" color="#ccc">
        <LayersOutline />
      </n-icon>
      <p>选择一个图层来编辑属性</p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import {
  NText,
  NButton,
  NButtonGroup,
  NIcon,
  NScrollbar,
  NForm,
  NFormItem,
  NInput,
  NInputNumber,
  NInputGroup,
  NSlider,
  NTag
} from 'naive-ui'
import {
  AddOutline,
  TrashOutline,
  EyeOutline,
  EyeOffOutline,
  LockClosedOutline,
  LockOpenOutline,
  CloseOutline,
  LayersOutline,
  ImageOutline,
  PersonOutline,
  ImagesOutline,
  SparklesOutline,
  VolumeHighOutline
} from '@vicons/ionicons5'
import { useEditorStore } from '../../stores/editor'
import type { EditorLayer, EditorKeyframe } from '../../stores/editor'
import { message } from '../../utils/message'

// 状态管理
const editorStore = useEditorStore()

// 本地状态
const layerProperties = ref<Partial<EditorLayer>>({})

// 计算属性
const selectedLayer = computed(() => editorStore.selectedLayer)
const hasSelection = computed(() => editorStore.selection.selectedLayers.length > 0)

const layersInOrder = computed(() => {
  return [...editorStore.layers].sort((a, b) => b.zIndex - a.zIndex)
})

const layerKeyframes = computed(() => {
  if (!selectedLayer.value) return []
  
  const layerTracks = editorStore.tracks.filter(track => track.layerId === selectedLayer.value!.id)
  const keyframes: EditorKeyframe[] = []
  
  layerTracks.forEach(track => {
    keyframes.push(...track.keyframes)
  })
  
  return keyframes.sort((a, b) => a.time - b.time)
})

// 方法
const isLayerSelected = (layerId: string) => {
  return editorStore.selection.selectedLayers.includes(layerId)
}

const selectLayer = (layerId: string, event: MouseEvent) => {
  const multiSelect = event.ctrlKey || event.metaKey
  console.log('PropertiesPanel selectLayer:', layerId, 'multiSelect:', multiSelect)
  editorStore.selectLayer(layerId, multiSelect)
}

const toggleLayerVisibility = (layerId: string) => {
  const layer = editorStore.layers.find(l => l.id === layerId)
  if (layer) {
    editorStore.updateLayer(layerId, { visible: !layer.visible })
  }
}

const toggleLayerLock = (layerId: string) => {
  const layer = editorStore.layers.find(l => l.id === layerId)
  if (layer) {
    editorStore.updateLayer(layerId, { locked: !layer.locked })
  }
}

const addLayer = () => {
  const newLayer = editorStore.addLayer({
    name: `图层 ${editorStore.layers.length + 1}`,
    visible: true,
    locked: false,
    type: 'image',
    position: { x: 0, y: 0 },
    scale: { x: 1, y: 1 },
    rotation: 0,
    opacity: 100
  })
  
  // 选择新图层
  editorStore.clearSelection()
  editorStore.selectLayer(newLayer.id)
  
  message.success('已添加新图层')
}

const deleteSelectedLayers = () => {
  const selectedLayers = editorStore.selection.selectedLayers
  selectedLayers.forEach(layerId => {
    editorStore.removeLayer(layerId)
  })
  
  message.success(`已删除 ${selectedLayers.length} 个图层`)
}

const updateLayerProperty = (property: string, value: any) => {
  if (!selectedLayer.value) return
  
  editorStore.updateLayer(selectedLayer.value.id, { [property]: value })
}

const addKeyframe = () => {
  if (!selectedLayer.value) return
  
  // 找到或创建图层对应的轨道
  let track = editorStore.tracks.find(t => t.layerId === selectedLayer.value!.id)
  
  if (!track) {
    track = editorStore.addTrack({
      name: selectedLayer.value.name,
      type: selectedLayer.value.type,
      layerId: selectedLayer.value.id,
      visible: true,
      locked: false,
      keyframes: []
    })
  }
  
  const currentTime = editorStore.playback.currentTime
  
  editorStore.addKeyframe(track.id, {
    time: currentTime,
    value: {
      position: { ...selectedLayer.value.position },
      scale: { ...selectedLayer.value.scale },
      rotation: selectedLayer.value.rotation,
      opacity: selectedLayer.value.opacity
    }
  })
  
  message.success('已添加关键帧')
}

const selectKeyframe = (keyframeId: string) => {
  editorStore.selectKeyframe(keyframeId)
}

const deleteKeyframe = (keyframeId: string) => {
  // 找到包含该关键帧的轨道
  for (const track of editorStore.tracks) {
    if (track.keyframes.some(kf => kf.id === keyframeId)) {
      editorStore.removeKeyframe(track.id, keyframeId)
      message.success('已删除关键帧')
      break
    }
  }
}

// 工具函数
const getLayerTypeIcon = (type: string) => {
  const icons = {
    image: ImageOutline,
    character: PersonOutline,
    scene: ImagesOutline,
    effect: SparklesOutline,
    audio: VolumeHighOutline
  }
  return icons[type] || ImageOutline
}

const getLayerTypeColor = (type: string) => {
  const colors = {
    image: '#52c41a',
    character: '#ff7875',
    scene: '#13c2c2',
    effect: '#fa8c16',
    audio: '#722ed1'
  }
  return colors[type] || '#8c8c8c'
}

const formatTime = (time: number) => {
  return time.toFixed(1)
}

// 监听选中图层变化
watch(selectedLayer, (newLayer) => {
  if (newLayer) {
    layerProperties.value = { ...newLayer }
  } else {
    layerProperties.value = {}
  }
}, { immediate: true })
</script>

<style lang="scss" scoped>
.properties-panel {
  display: flex;
  flex-direction: column;
  height: 100%;
  background: var(--card-color);
}

.panel-section {
  border-bottom: 1px solid var(--border-color);
  
  &:last-child {
    border-bottom: none;
    flex: 1;
  }
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background: var(--body-color);
  border-bottom: 1px solid var(--border-color);
}

.layers-list {
  max-height: 200px;
  overflow: hidden;
}

.layer-item {
  display: flex;
  align-items: center;
  padding: 8px 16px;
  cursor: pointer;
  transition: background-color 0.2s ease;
  
  &:hover {
    background: var(--hover-color);
  }
  
  &.selected {
    background: var(--primary-color-pressed);
    color: var(--primary-color);
  }
  
  .layer-controls {
    display: flex;
    gap: 4px;
    margin-right: 8px;
  }
  
  .layer-info {
    display: flex;
    align-items: center;
    gap: 8px;
    flex: 1;
    min-width: 0;
    
    .layer-name {
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      font-size: 14px;
    }
  }
}

.properties-content {
  padding: 16px;
}

.keyframes-content {
  padding: 8px 16px;
}

.keyframe-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px;
  border: 1px solid var(--border-color);
  border-radius: 4px;
  margin-bottom: 4px;
  cursor: pointer;
  transition: all 0.2s ease;
  
  &:hover {
    border-color: var(--primary-color);
  }
  
  .keyframe-time {
    font-family: monospace;
    font-size: 12px;
    color: var(--primary-color);
    min-width: 40px;
  }
  
  .keyframe-properties {
    flex: 1;
    display: flex;
    gap: 4px;
    flex-wrap: wrap;
  }
}

.empty-keyframes {
  text-align: center;
  padding: 20px;
  color: #999;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 200px;
  text-align: center;
  color: #999;
  
  p {
    margin-top: 16px;
  }
}
</style>
